package xm.erzhan.utils;

import org.json.JSONException;
import org.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import xm.erzhan.models.responseModels.NormRes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class Utils {

    static final String sKey = "abcdef0123456789";
    static final String ivParameter = "0123456789abcdef";

    public static String AESEncode(String sSrc) {
        String result = "";
        try {
            Cipher cipher;

            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            byte[] raw = sKey.getBytes();

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度

            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

            result = new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 此处使用BASE64做转码。
        return result;
    }

    // 解密
    public static String AESDecode(String sSrc) {
        try {
            byte[] raw = sKey.getBytes("ASCII");

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);

            String originalString = new String(original, "utf-8");

            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static NormRes checkToken(String token) {

        NormRes normRes = null;

        if (token == null) {
            normRes = new NormRes(401, "token invalid");

            return normRes;
        }

        // decode user string
        String userStr = Utils.AESDecode(token);
        String[] userArr = userStr.split("\\|");

        if (userArr.length != 2) {
            normRes = new NormRes(401, "token invalid");

            return normRes;
        }

        normRes = new NormRes(Code.CodeEnum.getCodeByType("OK"), userArr[0]);

        return normRes;
    }

    /**
     * change json string to map object
     * @param jsonString
     * @return Map Object
     * @throws JSONException
     */
    public static Map jsonToMap(String jsonString) throws JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);

        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;

        while (iterator.hasNext()) {

            key = (String) iterator.next();
            value = jsonObject.getString(key);

            result.put(key, value);
        }

        return result;
    }

    public static String mapToJson(Map map) {

        JSONObject jsonObject = new JSONObject(map);

        return jsonObject.toString();
    }

    public static Long getTimeNow() {

        return new Date().getTime() / 1000;
    }
}
